/**
 * @作者 Luke
 * @微信公号 欧诺的小书屋
 * @开源项目 $ http://7yue.pro
 * @免费专栏 $ http://course.7yue.pro
 * @我的课程 $ http://imooc.com/t/4294850
 * @创建时间 2020-6-21 21:59
 */
package io.github.talelin.latticy.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.github.talelin.autoconfigure.exception.ParameterException;
import io.github.talelin.latticy.dto.course.CreateOrUpdateCourseDTO;
import io.github.talelin.latticy.dto.course.CreateOrUpdateCoursewareDTO;
import io.github.talelin.latticy.mapper.CourseMapper;
import io.github.talelin.latticy.mapper.CoursewareMapper;
import io.github.talelin.latticy.model.CourseDO;
import io.github.talelin.latticy.model.CoursewareDO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CourseService extends ServiceImpl<CourseMapper, CourseDO> {

    @Autowired
    private CoursewareMapper coursewareMapper;

    /**
     * 根据teacherId查询所有课程
     * @param tid 老师id
     * @return List<CourseDO>
     */
    public List<CourseDO> getCoursesByTeacherId(Long tid){
        List<CourseDO> courses = this.baseMapper.getByTeacherId(tid);
        if (courses == null || courses.size() == 0) {
            return new ArrayList<>();
        }
        return courses;
    }

    /**
     * 根据关键字搜索课程
     * @param title 关键字
     * @return CourseDO
     */
    public List<CourseDO> getCourseByTitle(String title){
        List<CourseDO> courses = this.baseMapper.getCourseByTitle(title);
        if (courses == null || courses.size() == 0) {
            return new ArrayList<>();
        }
        return courses;
    }

    /**
     * 新增课程
     * @param validator CreateOrUpdateCourseDTO
     * @return boolean
     */
    public boolean createCourse(CreateOrUpdateCourseDTO validator){
        if (hasCourseExisted(validator)){
            return false;
        }
        // 创建课程
        CourseDO course = new CourseDO();
        BeanUtils.copyProperties(validator, course);
        course.setOnline(true);
        int insert = this.baseMapper.insert(course);
        return insert > 0;
    }

    /**
     * 上传课程课件
     * @param validator CreateOrUpdateCoursewareDTO
     */
    public void uploadCourseware(CreateOrUpdateCoursewareDTO validator){
        CoursewareDO courseware = new CoursewareDO();
        courseware.setCourseId(validator.getCourseId());
        courseware.setUrl(validator.getUrl());
        int result = this.coursewareMapper.insert(courseware);
        if (result <= 0) {
            throw new ParameterException("上传课件出错");
        }
    }


    /**
     * 判断是否有重复的课程名称
     * @param validator
     * @return
     */
    private boolean hasCourseExisted(CreateOrUpdateCourseDTO validator){
        int i = this.baseMapper.hasCourseExisted(validator.getTitle());
        return i > 0;
    }

}
